# -*- coding: utf-8 -*-

import json
import traceback

from torndb import Row

from mq import BaseConsumer
from mq import logger
from mq.code_mail_notice import CodeMailNotice
from mq.hotel_mail_notice import HotelMailNotice

class RedisMqConsumer(BaseConsumer):

    def init(self):
        self.redis_key = "kt:mq:event"
        self.redis_key_dead = "kt:mq:event:dead"
        self.timeout = 600
        self.remove_all = 0
        self.retry_default_count = 3

    def _retry(self, retry_data, origin_data):
        """
        队列时间retry处理, retry - 1

        :param retry_data: {\"data\":{\"wechat_id\":\"a3cc0d9b07444ae68bfdc6c074fd05a4\",\"scene_id\":2},\"event\":1,\"retry\":3}
        :return:
        """

        retry_data['retry'] = (retry_data.retry - 1 if retry_data.retry <= 10 else 9) if retry_data.get(
            "retry") else self.retry_default_count
        event_data = json.dumps(retry_data)

        pipe = self.redis.pipeline()
        pipe.lrem(self.redis_key_dead, self.remove_all, origin_data)
        pipe.lpush(self.redis_key, event_data)
        pipe.execute()

    def dispatch(self):
        """
        队列分发

        :return:
        """

        while True:

            try:
                data = self.redis.brpoplpush(self.redis_key, self.redis_key_dead, self.timeout)
                if data:
                    ok = None
                    event_data = Row(json.loads(data))
                    if event_data and event_data.event:
                        logger.info("mq event {}".format(event_data))
                        if event_data.event == 2:
                            ok = CodeMailNotice().runner(Row(event_data.data))
                        elif event_data.event == 3:
                            ok = HotelMailNotice().runner(Row(event_data.data))
                        else:
                            logger.error("type is None value:%s" % event_data.event)

                        if ok:
                            self.redis.lrem(self.redis_key_dead, self.remove_all, data)
                        else:
                            # retry 不为0，做retry处理
                            if event_data.get("retry", self.retry_default_count):
                                logger.debug("event_data.retry : {}".format(event_data.get("retry")))
                                self._retry(event_data, data)

                            else:
                                logger.debug("process failed!")
                    else:
                        logger.error("event_data is None")
                else:
                    logger.debug("data is None")

            except Exception, e:
                traceback.print_exc()
                logger.error(e)

if __name__ == '__main__':
    mqConsumer = RedisMqConsumer()
    mqConsumer.dispatch()
